{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import shutil\n",
    "import os\n",
    "import cv2\n",
    "import math\n",
    "import numpy as np\n",
    "from ultralytics import YOLO\n",
    "\n",
    "from ultralytics.utils.checks import check_imshow\n",
    "from ultralytics.utils.plotting import Annotator, colors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def crop_video(input_video_path, output_video_path, crop_coords):\n",
    "    cap = cv2.VideoCapture(input_video_path)\n",
    "\n",
    "    # Define the codec and create VideoWriter object\n",
    "    fourcc = cv2.VideoWriter_fourcc(*'MJPG')\n",
    "    out = None\n",
    "\n",
    "    max_x1, max_y1, max_x2, max_y2 = crop_coords\n",
    "\n",
    "    while cap.isOpened():\n",
    "        ret, frame = cap.read()\n",
    "        if not ret:\n",
    "            break\n",
    "\n",
    "        # Crop the frame\n",
    "        cropped_frame = frame[max_y1:max_y2, max_x1:max_x2]\n",
    "\n",
    "        # Initialize VideoWriter with the shape of the cropped frame\n",
    "        if out is None:\n",
    "            out = cv2.VideoWriter(output_video_path, fourcc, cap.get(cv2.CAP_PROP_FPS), (cropped_frame.shape[1], cropped_frame.shape[0]))\n",
    "\n",
    "        # Write the cropped frame\n",
    "        out.write(cropped_frame)\n",
    "\n",
    "    # Release everything when job is finished\n",
    "    cap.release()\n",
    "    if out is not None:\n",
    "        out.release()\n",
    "    cv2.destroyAllWindows()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def extrac_mmbox(inp_video_dir, opt_video_dir, model):\n",
    "    \n",
    "    if not os.path.exists(opt_video_dir):\n",
    "        os.makedirs(opt_video_dir)\n",
    "    \n",
    "    for root, dirs, filenames in os.walk(inp_video_dir):\n",
    "        for filename in filenames:\n",
    "            \n",
    "            video_file_path = os.path.join(root, filename)\n",
    "            results = model.predict(video_file_path, stream=True, conf=0.3, classes=0)\n",
    "    \n",
    "            max_x1, max_y1 = float('inf'), float('inf')\n",
    "            max_x2, max_y2 = 0, 0\n",
    "\n",
    "            max_people = 0\n",
    "\n",
    "            for r in results:\n",
    "\n",
    "                people = 0\n",
    "\n",
    "                for rr in r:\n",
    "                    #print(rr.boxes)\n",
    "                    #print(rr.boxes.xyxy[0][0].item())\n",
    "\n",
    "                    max_x1 = min(max_x1, rr.boxes.xyxy[0][0].item())\n",
    "                    max_y1 = min(max_y1, rr.boxes.xyxy[0][1].item())\n",
    "                    max_x2 = max(max_x2, rr.boxes.xyxy[0][2].item())\n",
    "                    max_y2 = max(max_y2, rr.boxes.xyxy[0][3].item())\n",
    "\n",
    "                    #print(\"\\n\",\"new box\",\"\\n\")\n",
    "                    people += 1\n",
    "\n",
    "                if people > 1:\n",
    "                    max_people = max(max_people, people)\n",
    "\n",
    "                #print(\"\\n\",\"new frame\",\"\\n\")\n",
    "                \n",
    "            output_video_path = os.path.join(opt_video_dir, filename)   \n",
    "            \n",
    "            if max_people > 1 :\n",
    "                \n",
    "                crop_coords = (math.ceil(max_x1), math.ceil(max_y1), math.ceil(max_x2), math.ceil(max_y2))  \n",
    "\n",
    "                crop_video(video_file_path, output_video_path, crop_coords)\n",
    "                \n",
    "            else:\n",
    "                \n",
    "                shutil.copy(video_file_path, output_video_path)\n",
    "                \n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = YOLO('yolov8x.pt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "inp_video_dir = 'path to the input videos'\n",
    "opt_video_dir = 'path to the output videos'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "extrac_mmbox(inp_video_dir, opt_video_dir, model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "platformtest",
   "language": "python",
   "name": "platformtest"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
